<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #board {
            width: 1000px;
            height: 500px;
            outline: 10px solid red;
            position: relative;
            margin: 0 auto;
        }

        .snake {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            background-color: green;
            position: absolute;
        }

        #snake-head {
            background-color: black;
            z-index: 1;
        }
    </style>
</head>
<body>

<section id="board">
    <div class="snake" id="snake-head"></div>
    <div class="snake"></div>
    <div class="snake"></div>
    <div class="snake"></div>
    <div class="snake"></div>
</section>

<script type="text/javascript">
    const [leftKey, topKey, rightKey, bottomKey] = [37, 38, 39, 40];
    const [horizontalStep, verticalStep] = [50, 50];
    const [snakeWidth, snakeHeight] = [50, 50];
    const [boardWidth, boardHeight] = [1000, 500];

    window.onload = () => {
        document.onkeydown = () => {
            snakeBodyMove();
            snakeHeadMove();
        };
    };

    let snakeBodyMove = () => {
        let snakes = document.querySelectorAll(".snake");
        for (let i = snakes.length - 1; i > 0; i--) {
            snakes[i]["style"]["left"] = snakes[i - 1]["style"]["left"];
            snakes[i]["style"]["top"] = snakes[i - 1]["style"]["top"];
        }
    };

    let snakeHeadMove = event => {
        let snakeHead = document.querySelector("#snake-head");
        let ev = event || window.event;
        switch (ev.keyCode) {
            case leftKey :
                if (snakeHead.offsetLeft <= 0) return;
                snakeHead["style"]["left"] = snakeHead.offsetLeft - horizontalStep + "px";
                break;
            case topKey :
                if (snakeHead.offsetTop <= 0) return;
                snakeHead["style"]["top"] = snakeHead.offsetTop - verticalStep + "px";
                break;
            case rightKey :
                if (snakeHead.offsetLeft >= boardWidth - snakeWidth) return;
                snakeHead["style"]["left"] = snakeHead.offsetLeft + horizontalStep + "px";
                break;
            case bottomKey :
                if (snakeHead.offsetTop >= boardHeight - snakeHeight) return;
                snakeHead["style"]["top"] = snakeHead.offsetTop + verticalStep + "px";
                break;
        }
    }
</script>

</body>
</html>